package com.chenju.easyshotjava.core;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class RectangleCapture extends JPanel {
    private Point startPoint;
    private Point endPoint;
    private Rectangle selectionRect;
    private CaptureListener listener;

    public RectangleCapture(JWindow window) {
        this.setOpaque(false); // 使窗口透明
        this.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));

        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                startPoint = e.getPoint();
                selectionRect = new Rectangle(startPoint);
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                endPoint = e.getPoint();
                selectionRect = new Rectangle(Math.min(startPoint.x, endPoint.x),
                        Math.min(startPoint.y, endPoint.y),
                        Math.abs(startPoint.x - endPoint.x),
                        Math.abs(startPoint.y - endPoint.y));
                if (listener != null) {
                    listener.onCapture(selectionRect);
                }
                window.dispose(); // 释放窗口
            }
        });

        addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                endPoint = e.getPoint();
                selectionRect.setBounds(Math.min(startPoint.x, endPoint.x),
                        Math.min(startPoint.y, endPoint.y),
                        Math.abs(startPoint.x - endPoint.x),
                        Math.abs(startPoint.y - endPoint.y));
                repaint();
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (selectionRect != null) {
            g.setColor(new Color(0, 0, 255, 100)); // 半透明蓝色
            g.fillRect(selectionRect.x, selectionRect.y, selectionRect.width, selectionRect.height);
            g.setColor(Color.RED);
            g.drawRect(selectionRect.x, selectionRect.y, selectionRect.width, selectionRect.height);
        }
    }

    public void addCaptureListener(CaptureListener listener) {
        this.listener = listener;
    }

    public interface CaptureListener {
        void onCapture(Rectangle rect);
    }
}